package com.hbk.service.impl;

import com.hbk.base.common.CommonResult;
import com.hbk.base.common.Ref;
import com.hbk.base.util.TimeUtil;
import com.hbk.entity.FriendLink;
import com.hbk.mapper.FriendLinkMapper;
import com.hbk.param.FriendLinkParam;
import com.hbk.service.ICacheService;
import com.hbk.service.IFriendLinkService;
import com.hbk.vo.FriendLinkVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class FriendLinkServiceImpl implements IFriendLinkService {

    @Resource
    private FriendLinkMapper friendLinkMapper;
    @Resource
    private ICacheService cacheService;

    public CommonResult add(FriendLinkParam.AddParam param){
        FriendLink link = new FriendLink();
        link.setTitle(param.getTitle());
        link.setUrl(param.getUrl());
        link.setOrderNum(param.getOrderNum());
        link.setCreateTime(new Date());
        link.setUpdateTime(new Date());
        friendLinkMapper.insert(link);
        cacheService.deleteIndexCache();
        return Ref.ok();
    }

    public CommonResult modify(FriendLinkParam.ModifyParam param){
        FriendLink link = friendLinkMapper.selectById(param.getId());
        if(link==null){
            return Ref.error("找不到该链接");
        }
        link.setTitle(param.getTitle());
        link.setUrl(param.getUrl());
        link.setOrderNum(param.getOrderNum());
        link.setUpdateTime(new Date());
        friendLinkMapper.updateById(link);
        cacheService.deleteIndexCache();
        return Ref.ok();
    }

    public CommonResult delete(FriendLinkParam.DeleteParam param){
        friendLinkMapper.deleteById(param.getId());
        cacheService.deleteIndexCache();
        return Ref.ok();
    }

    public CommonResult listAll(){
        List<FriendLink> list = friendLinkMapper.listAll();
        List<FriendLinkVo.ListAllVo> vos = new ArrayList<>();
        for(int i=0; i<list.size(); i++){
            FriendLinkVo.ListAllVo vo = new FriendLinkVo.ListAllVo();
            FriendLink link = list.get(i);
            vo.setIndexNum(i+1);
            vo.setId(link.getId());
            vo.setOrderNum(link.getOrderNum());
            vo.setTitle(link.getTitle());
            vo.setUrl(link.getUrl());
            vo.setCreateTime(TimeUtil.formaterYYYYMMddHHmm(link.getCreateTime()));
            vo.setUpdateTime(TimeUtil.formaterYYYYMMddHHmm(link.getUpdateTime()));
            vos.add(vo);
        }
        return Ref.ok(vos);
    }
}
